package com.faithbj.printer.service.Impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.springframework.stereotype.Component;

import cn.com.jautoitx.Keyboard;

import com.faithbj.printer.logger.Logger;
import com.faithbj.printer.model.ExcelElement;
import com.faithbj.printer.service.LoginService;
import com.faithbj.printer.util.Constants;
import com.faithbj.printer.util.DateUtils;
import com.faithbj.printer.util.ExcelUtil;
import com.faithbj.printer.util.FileUtil;
import com.faithbj.printer.util.KeyUtils;
import com.faithbj.printer.util.PropertiesUtil;

@Component("loginService")
public class LoginServiceImpl implements LoginService {

	@Resource
	private Constants constants;

	@Logger
	private Log log;

	@Override
	public boolean login(WebDriver driver) {
		log.error("robot:登录开始...");
		driver.get(constants.getBaseurl() + "/prpall/index.jsp");

		driver.switchTo().frame("fraInterface");
		
		WebElement userCode = driver.findElement(By.name("UserCode"));
		userCode.sendKeys(constants.getUsername());
		
		WebElement password = driver.findElement(By.name("Password"));
		password.sendKeys(constants.getPasswd());
		
		WebElement loginRiskCode = driver.findElement(By.name("RiskCode"));
		loginRiskCode.sendKeys("05");
		
		Select riskCodeSelect = new Select(driver.findElement(By.name("RiskCodeSelect")));
		riskCodeSelect.selectByValue("0509");
		
		WebElement submit = driver.findElement(By.name("image"));
		submit.click();
//		driver.switchTo().defaultContent(); 
		log.error("ok:登录");
		return true;
	}

	@Override
	public boolean queryGuarantee(WebDriver driver, String poaCode) {
		log.error("robot:查询保单:" + poaCode);
		driver.get(constants.getBaseurl()
				+ "/prpall/commonship/sff/UIPreConfirmQueryInput.jsp");
		WebElement poaCodeEle = driver.findElement(By.name("PoaCode"));
		poaCodeEle.sendKeys(poaCode);
		
		WebElement validStartDate = driver.findElement(By.name("validStartDate"));
		validStartDate.clear();
		
		String threeDaysAgo=DateUtils.formateDate2String("yyyy-MM-dd", DateUtils.getDaysAgo(3));
		validStartDate.sendKeys(threeDaysAgo);
		
		WebElement btn = driver.findElement(By.name("btnSubmit"));
		btn.click();
		log.error("ok:查询保单" + poaCode);
		return true;
	}

	@Override
	public boolean confirmGuarantee(WebDriver driver) {
		log.error("robot:确认保单");
		try{
		WebElement radio = driver.findElement(By.name("checkRadio"));
		radio.click();
			WebElement btn = driver.findElement(By
					.xpath("//form/table[2]//tr/td[2]/input"));
			btn.click();
		}
		catch(NoSuchElementException  noE){
			log.error("fatal:您给的保单号没有交易号,程序退出！");
			System.exit(-1);
		}
		log.error("ok:确认保单");
		return true;
	}

	@Override
	public boolean confirmResult(WebDriver driver) throws TimeoutException {
		log.error("robot:投保确认结果");
		
		List<WebElement> elems= driver.findElements(By.cssSelector("td.common"));
		int countdown=100;
		
		for(int i=0;i<countdown && elems.size()==0;i++){
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.exit(-1);
			}
			driver.navigate().back();
			log.error("retry: 投保确认结果");
			confirmGuarantee(driver);
			elems= driver.findElements(By.cssSelector("td.common"));
		}

		String original=elems.get(0).getText().trim();
		String[] res=original.split("\n");
		
		if(res.length==3){
			Constants.data = new String[]{res[1],res[2]};
			FileUtil.appendMethodB(constants.getInsurancePolicy(), res[1]+","+res[2]+"\r\n");
			log.error("ok:确认完成，获取保单号--"+Arrays.asList(Constants.data));
			return true;
		}
		else if(res.length==2){
			Constants.data = new String[]{res[1]};
			FileUtil.appendMethodB(constants.getInsurancePolicy(), res[1]+"\r\n");
			log.error("ok:确认完成，获取保单号--"+Arrays.asList(Constants.data));
			return true;			
		}
		else{
			log.error("fatal: 确认失败，保单数据异常,！ data:"+original);
		}
		return false;
	}
	
	@Override
	public boolean printingPoolQuery(WebDriver driver, String bizNo){
		this.log.error("robot：打印池查询页面--快捷打印");
		driver.get(this.constants.getBaseurl()+"/prpall/commonship/pub/UIPrPoEnPrintPoolQueryInput.jsp?GroupFlag=0");
		WebElement element = driver.findElement(By.name("BizNo"));
		element.sendKeys(bizNo);
		WebElement btn = driver.findElement(By.name("buttonPrint"));
		btn.click();
		log.error("ok:打印池查询页面");
		return true;
	}

	@Override
	public boolean certificatePrint(WebDriver driver){
		log.error("robot:单证打印-商业险保单");
		Select locTypeCode = new Select(driver.findElement(By.name("LocTypeCode")));
		locTypeCode.selectByIndex(1);
		//修改印刷流水号
		checkSerial(driver,"SerialNo",Constants.DOC_PRINT_SERIAL);
		driver.findElement(By.name("buttonSubmit")).click();
      
		KeyUtils.sleepMe(7000);
		KeyUtils.pureTab();
		KeyUtils.enter();	
		
		KeyUtils.sleepMe(7000);	
		KeyUtils.enter();
		KeyUtils.closeWinAltF();
		
		KeyUtils.sleepMe(3000);	
		Keyboard.send("{ENTER}");
		KeyUtils.closeWinAltF();
		
        KeyUtils.sleepMe(2000);
		log.error("ok:单证打印-商业险保单");		
		return true;
	}
	
	@Override
	public boolean mandatoryInsurancePrint(WebDriver driver){
		log.error("robot:机动车交通事故责任强制保险单（上海）");
		Select locTypeCode = new Select(driver.findElement(By.name("LocTypeCode")));
		locTypeCode.selectByIndex(0);

		//修改印刷流水号
		checkSerial(driver,"SerialNo",Constants.COMPULSORY_INSURANCE_SERIAL);
		driver.findElement(By.name("buttonSubmit")).click();
		
		KeyUtils.sleepMe(6000);
		KeyUtils.pureTab();
		KeyUtils.sleepMe(1000);
		KeyUtils.enter();	
		
		//最后打印页面
//		KeyUtils.sleepMe(3000);	
//		KeyUtils.altTab();	
		KeyUtils.sleepMe(3000);	
		KeyUtils.enter();	
		KeyUtils.sleepMe(1000);	
		KeyUtils.closeWinAltF();
		//back print
        KeyUtils.sleepMe(3000);
        KeyUtils.enter();
        KeyUtils.sleepMe(3000);
    	KeyUtils.closeWinAltF();
        KeyUtils.sleepMe(2000);
        log.error("ok: 机动车交通事故责任强制保险单（上海）");
		return true;
	}

	@Override
	public boolean insuranceFlagPrint(WebDriver driver){
		log.error("robot: 保险标志打印");
		//修改发票信息
		checkSerial(driver,"SerialNo1",Constants.COMPULSORY_MARKING_SERIAL);
		driver.findElement(By.xpath("//table[2]//input[@name='buttonSubmit']")).click();
		
		KeyUtils.sleepMe(5000);
		KeyUtils.pureTab();
		KeyUtils.sleepMe(1000);
		KeyUtils.enter();	
		
		//最后alert页面
		KeyUtils.sleepMe(4000);	
		Keyboard.send("!{TAB}");
		KeyUtils.sleepMe(5000);	
		KeyUtils.enter();	
		KeyUtils.sleepMe(5000);	
		KeyUtils.closeWinAltF();
		
		//back print
        KeyUtils.sleepMe(5000);
        KeyUtils.enter();
        KeyUtils.sleepMe(3000);
    	KeyUtils.closeWinAltF();
        KeyUtils.sleepMe(1000);
        log.error("ok: 保险标志打印");        
		return true;
	}
	
	
	@Override
	public boolean invoiceQuery(WebDriver driver, String bizNo,Integer order) {
		log.error("robot：保费发票打印查询页面");
		driver.get(this.constants.getBaseurl()+"/prpall/commonship/sff/UIPremiumInvoiceQueryInputNew.jsp");
		WebElement policyNo = driver.findElement(By.name("PolicyNo"));
		policyNo.sendKeys(bizNo);
		
		WebElement btn = driver.findElement(By.name("buttonSubmit1"));
		btn.click();
		
		//勾选要打印的发票
		WebElement checkbtn = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[2]/td/input"));
		checkbtn.click();
		WebElement mergePrint = driver.findElement(By.xpath("/html/body/form/table[3]/tbody/tr/td/input[8]"));
		mergePrint.click();
		
		//修改发票信息
		checkSerial(driver,"VisaSerialNo",Constants.INVOICE_SERIAL);
		
		WebElement formatbtn = driver.findElement(By.name("buttonSubmitOKNew3"));
		formatbtn.click();
		
		KeyUtils.sleepMe(6000);
		if(order==0)
		{
			KeyUtils.pageScaleAndSetting(Constants.LEFT,"0","0","5","4");
		}
		else
			KeyUtils.pageScaleAndSetting(Constants.LEFT,"0","0","0","0");
		KeyUtils.sleepMe(1000);
		KeyUtils.pureTab();
		KeyUtils.enter();
		KeyUtils.sleepMe(2000);
		KeyUtils.enter();
		
        KeyUtils.sleepMe(2000);
    	KeyUtils.closeWin();
        KeyUtils.sleepMe(2000);
		return true;
	}

	@Override
	public boolean insuranceFlagQuery(WebDriver driver) {
		log.error("robot: 保险标志打印");
		
		//修改发票信息
		checkSerial(driver,"SerialNo1",Constants.COMPULSORY_MARKING_SERIAL);
		
		WebElement btn = driver.findElement(By.xpath("//table[2]//input[@name='buttonSubmit']"));
		btn.click();
		log.error("ok:单证打印");
		return true;
	}
	
	public boolean accidentLogin(WebDriver driver){
		log.error("robot:驾乘无忧意外险登录");
		driver.get(constants.getBaseurl() + "/prpall/");
		driver.get(constants.getBaseurl() + "/prpall/index.jsp");
		driver.switchTo().frame("fraInterface");
		WebElement userCode = driver.findElement(By.name("UserCode"));
		userCode.sendKeys(constants.getUsername());
		WebElement password = driver.findElement(By.name("Password"));
		password.sendKeys(constants.getPasswd());
		WebElement loginRiskCode = driver.findElement(By.name("RiskCode"));
		loginRiskCode.sendKeys("27");
		Select riskCodeSelect = new Select(driver.findElement(By.name("RiskCodeSelect")));
		riskCodeSelect.selectByValue("2700");
		WebElement submit = driver.findElement(By.xpath("//input[@name='image']"));
		submit.click();
		log.error("ok:驾乘无忧意外险登录");
		return true;
	}
	
	
	@Override
	public boolean accidentQuery(WebDriver driver, String bizNo, Integer order) {
		log.error("robot:驾乘无忧意外险打印");
	//填写打印流水号
		driver.get(constants.getBaseurl()+"/prpall/commonship/pub/UIPrPoEnPrintPoolQueryInput.jsp?GroupFlag=0");
		KeyUtils.sleepMe(2000);
		
		String lastPage = driver.getWindowHandle();
		for(String handle : driver.getWindowHandles()){
			if(!handle.equals(lastPage)){
				driver.switchTo().window(handle);
				driver.close();
			}
		}
		driver.switchTo().window(lastPage);
		
		WebElement bizNoInput = driver.findElement(By.name("BizNo"));
		bizNoInput.sendKeys(bizNo);
		WebElement btn = driver.findElement(By.name("buttonPrint"));
		btn.click();
	//选择意健险
		Select locTypeCode = new Select(driver.findElement(By.name("LocTypeCode")));
		locTypeCode.selectByValue("ABK066F32009A");
		KeyUtils.sleepMe(1000);
	//修改印刷流水号
		checkSerial(driver,"SerialNo",Constants.ACCIDENT_PRINT_SERIAL);
		
		lastPage = driver.getWindowHandle();
		
		WebElement buttonSubmit = driver.findElement(By.name("buttonSubmit"));
		buttonSubmit.click();
		
		KeyUtils.sleepMe(3000);
		Alert alert=null;
		try{
			alert=driver.switchTo().alert();
			alert.accept();
		}
		catch(NoAlertPresentException  nape){
			log.error("ok:这是个正常单号，不用确认了！");
		}
		
//驾乘无忧打印设置
//		KeyUtils.sleepMe(3000);
//		KeyUtils.pageSettingAndPrint("9","24.69","20","0");
		
		KeyUtils.sleepMe(3000);
		for(String handle : driver.getWindowHandles()){
			if(!handle.equals(lastPage)){
				driver.switchTo().window(handle);
				break;
			}
		}
		
		
		KeyUtils.sleepMe(1000);
		WebElement printbtn = driver.findElement(By.name("buttonPrint"));
	    
		printbtn.click();
		
        KeyUtils.sleepMe(4000);
		driver.switchTo().alert().accept();
		
        KeyUtils.sleepMe(5000);
		KeyUtils.enterKey();
        KeyUtils.sleepMe(5000);
        
		lastPage = driver.getWindowHandle();
		driver.close();
		for(String handle : driver.getWindowHandles()){
			if(!handle.equals(lastPage)){
				driver.switchTo().window(handle);
				break;
			}
		}
		
		log.error("ok:驾乘无忧意外险打印");
		return true;
	}
	
	
	@Override
	public boolean accidentInvoicePrint(WebDriver driver, String bizNo,
			Integer order) {
		log.error("robot:意外险发票打印");
		driver.get(constants.getBaseurl() + "/prpall/commonship/sff/UIPremiumInvoiceQueryInputNew.jsp");
		WebElement policyNo = driver.findElement(By.name("PolicyNo"));
		policyNo.sendKeys(bizNo);	
		WebElement riskCode = driver.findElement(By.name("RiskCode"));
		riskCode.clear();	
		WebElement buttonSubmit1 = driver.findElement(By.name("buttonSubmit1"));
		buttonSubmit1.click();
		//保费勾选
//		WebElement checkInput = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[2]/td/input"));
		WebElement checkInput = driver.findElement(By.name("check"));
		checkInput.click();
		WebElement mergePrint = driver.findElement(By.xpath("/html/body/form/table[3]/tbody/tr/td/input[8]"));
		mergePrint.click();
		//修改发票信息
		checkSerial(driver,"VisaSerialNo",Constants.ACCIDENT_SERIAL);
		
//		Select visaCodeIndex = new Select(driver.findElement(By.name("VisaCodeIndex")));
//		visaCodeIndex.selectByIndex(2);
		
		String lastPage = driver.getWindowHandle();
		
		WebElement formatbtn = driver.findElement(By.name("buttonSubmitOKNew3"));
		formatbtn.click();
		
		KeyUtils.sleepMe(3000);
		for(String handle : driver.getWindowHandles()){
			if(!handle.equals(lastPage)){
				driver.switchTo().window(handle);
				break;
			}
		}
		
		//准备打印A3 0.0.0.0
		KeyUtils.sleepMe(3000);
		KeyUtils.pageScaleAndSetting(Constants.LEFT,"0","0","0","0");
		
		WebElement printbtn = driver.findElement(By.xpath("/html/body/div/div/p/table/tbody/tr/td/input"));
		printbtn.click();
		KeyUtils.enterKey();		
		KeyUtils.sleepMe(3000);
		lastPage = driver.getWindowHandle();
		driver.close();
		for(String handle : driver.getWindowHandles()){
			if(!handle.equals(lastPage)){
				driver.switchTo().window(handle);
				break;
			}
		}
		
		log.error("ok:意外险发票打印");
		return true;
	}

	@Override
	public void checkResult(WebDriver driver,boolean result) {
        if(result==false){
        	log.error("fatal:系统错误，请检查流程！");
      	    driver.quit();
      	    System.exit(-1);
        }
	}
	
	private void checkSerial(WebDriver driver,String inputName,String sequence) {
		int serial=Integer.parseInt(PropertiesUtil.readValue(sequence));//流水号+1
		String serialStr=String.valueOf(serial);
		WebElement serialNo = driver.findElement(By.name(inputName));
		serialNo.clear();
		serialNo.sendKeys(serialStr);
		serial=serial+1;
		PropertiesUtil.writeProperties(sequence, String.valueOf(serial));//写回配置文件
	}
	
	@Override
	public boolean printExcel(String[] data) {
		log.error("robot:Excel打印");
		List<ExcelElement> elements = new ArrayList<ExcelElement>();
		String serialStr=null;
		if(data.length==1)
		{
			if(data[0].substring(8,9).equals("9"))
			{
				serialStr=PropertiesUtil.readValue(Constants.DOC_PRINT_SERIAL);
				int serial=Integer.parseInt(serialStr);//流水号+1
				serial=serial+1;
				PropertiesUtil.writeProperties(Constants.DOC_PRINT_SERIAL, String.valueOf(serial));//写回配置文件
			}
			else{
				serialStr=PropertiesUtil.readValue(Constants.COMPULSORY_INSURANCE_SERIAL);
				int serial=Integer.parseInt(serialStr);//流水号+1
				serial=serial+1;
				PropertiesUtil.writeProperties(Constants.COMPULSORY_INSURANCE_SERIAL, String.valueOf(serial));//写回配置文件
			}
		}
		else
		{
			for(int i=0;i<data.length;i++){
				if(data[i].substring(8,9).equals("7"))
				{
					serialStr=PropertiesUtil.readValue(Constants.COMPULSORY_INSURANCE_SERIAL);
					int serial=Integer.parseInt(serialStr);//流水号+1
					serial=serial+1;
					PropertiesUtil.writeProperties(Constants.COMPULSORY_INSURANCE_SERIAL, String.valueOf(serial));//写回配置文件					
					break;
				}
			}
		}
		
		
		elements.add(new ExcelElement(1,6,serialStr));
		if(data.length==2){
			elements.add(new ExcelElement(40,3,data[0]));
			elements.add(new ExcelElement(40,6,data[1]));
		}
		else{
			elements.add(new ExcelElement(40,3,data[0]));
		}
		try {
			ExcelUtil.printExcel(elements);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		log.error("ok:Excel打印");
		return true;
	}

	@Override
	public boolean printExcelTxt(String[] data) {
		String serialStr=null;
		List<String> elements = new ArrayList<String>();
		if(data.length==1)
		{
			if(data[0].substring(8,9).equals("9"))
			{
				serialStr=PropertiesUtil.readValue(Constants.DOC_PRINT_SERIAL);
			}
			else
				serialStr=PropertiesUtil.readValue(Constants.COMPULSORY_INSURANCE_SERIAL);
		}
		else
		{
			for(int i=0;i<data.length;i++){
				if(data[i].substring(8,9).equals("7"))
				{
					serialStr=PropertiesUtil.readValue(Constants.COMPULSORY_INSURANCE_SERIAL);
					break;
				}
			}
		}
		
		
		
		if(data.length==2){
			elements.add(data[0]);
			elements.add(data[0]);
		}
		else{
			elements.add(data[0]);
		}
		
		return false;
	}

}